from OpenSSL import crypto
import datetime
from Crypto.PublicKey import RSA

def generate_self_signed_cert():
    # 生成密钥
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)

    # 生成证书
    cert = crypto.X509()
    cert.get_subject().CN = "localhost"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha256')

    # 写入文件
    with open("cert.pem", "wb") as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open("key.pem", "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

def generate_rsa_key():
    # 生成RSA密钥对
    key = RSA.generate(1024)
    
    # 获取公钥
    public_key = key.publickey().export_key()
    
    # 将字节转换为字符串并去除头尾标记和换行符
    public_key_str = public_key.decode('utf-8')
    public_key_str = public_key_str.replace('-----BEGIN PUBLIC KEY-----\n', '')
    public_key_str = public_key_str.replace('\n-----END PUBLIC KEY-----', '')
    
    print("生成的公钥:")
    print(public_key_str)
    
if __name__ == "__main__":
    generate_self_signed_cert()
    generate_rsa_key() 